package com.sino.config.server.service;

import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.nutz.lang.Strings;
import org.nutz.repo.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import com.sino.config.server.service.ProfileChecker.ProfileCheckerProperties;

/**
 * @author kerbores
 *
 */
@Component
@EnableConfigurationProperties(ProfileCheckerProperties.class)
public class ProfileChecker {

	@Autowired
	ProfileCheckerProperties profileCheckerProperties;

	public boolean isProtectProfile(String profile) {
		List<String> ps = profileCheckerProperties.getProtectProfiles();
		Collections.sort(ps);
		return Collections.binarySearch(ps, profile) >= 0;
	}

	public boolean check(HttpServletRequest request, String profile) {
		if (!isProtectProfile(profile)) {
			return true;
		}
		String auth = request.getHeader("Authorization");
		if (auth != null && (auth.length() > 6)) {
			auth = auth.substring(6, auth.length());
			String decodedAuth = getFromBASE64(auth);
			// 比对一下
			if (Strings.equals(decodedAuth, String.format("%s:%s", profileCheckerProperties.getUserName(), profileCheckerProperties.getPassword()))) {
				request.getSession().setAttribute("auth", decodedAuth);
				return true;
			}
		}
		return false;
	}

	private String getFromBASE64(String s) {
		if (s == null)
			return null;
		try {
			byte[] b = Base64.decode(s);
			return new String(b);
		} catch (Exception e) {
			return null;
		}
	}

	@ConfigurationProperties(prefix = "profile.checker")
	public static class ProfileCheckerProperties {

		List<String> protectProfiles;

		String userName;

		String password;

		/**
		 * @return the protectProfiles
		 */
		public List<String> getProtectProfiles() {
			return protectProfiles;
		}

		/**
		 * @param protectProfiles
		 *            the protectProfiles to set
		 */
		public void setProtectProfiles(List<String> protectProfiles) {
			this.protectProfiles = protectProfiles;
		}

		/**
		 * @return the userName
		 */
		public String getUserName() {
			return userName;
		}

		/**
		 * @param userName
		 *            the userName to set
		 */
		public void setUserName(String userName) {
			this.userName = userName;
		}

		/**
		 * @return the password
		 */
		public String getPassword() {
			return password;
		}

		/**
		 * @param password
		 *            the password to set
		 */
		public void setPassword(String password) {
			this.password = password;
		}

	}

}
